package com.qf.service.impl;

import com.qf.config.RedisKey;
import com.qf.dao.mapper.QfCourseDao;
import com.qf.pojo.dto.QfCourse;
import com.qf.pojo.resVo.BaseResult;
import com.qf.pojo.resVo.CourseTeacherResp;
import com.qf.service.CourseService;
import org.hibernate.annotations.common.util.impl.LoggerFactory;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    QfCourseDao qfCourseDao;
    @Autowired
    RedisTemplate redisTemplate;

    //声明日志
    private static Logger logger  = LoggerFactory.logger(CourseServiceImpl.class);

    @Override
    public BaseResult findCourseByClassify(Integer id,Integer page,Integer size) {
        //1.判断Redis中是否有该key值
        Boolean aBoolean = redisTemplate.hasKey(RedisKey.COURSE_KEY + id.toString());
        int start = (page-1)*size;
        if (aBoolean){
            logger.debug("课程信息从Redis进行查询");
            List range = redisTemplate.opsForList().range(RedisKey.COURSE_KEY + id.toString(), start, start+size-1);
            //通过Redis的List获取到总数
            Long total = redisTemplate.opsForList().size(RedisKey.COURSE_KEY + id.toString());
            return new BaseResult(1,"查询成功",range,total);
        }else{
            //通过两表联查去数据库查询出传入的课程分类下的课程信息
            logger.debug("课程信息从数据库进行查询");
            List<QfCourse> qfCourseList =qfCourseDao.findCourseByClassify(id);
           //判断当前数据库中是否有该数据
            if (qfCourseList!=null&&qfCourseList.size()>0){
                redisTemplate.opsForList().leftPushAll(RedisKey.COURSE_KEY + id.toString(),qfCourseList);
                List range = redisTemplate.opsForList().range(RedisKey.COURSE_KEY + id.toString(), start, start+size-1);
                Long total = redisTemplate.opsForList().size(RedisKey.COURSE_KEY + id.toString());
                return new BaseResult(1,"查询成功",range,total);
            }
           return new BaseResult(1,"查询成功",qfCourseList,null);
        }


    }

    @Override
    public BaseResult findCourseDetailById(Integer id) {
        //1.查询该课程的详细信息，两表联查
        CourseTeacherResp courseTeacherResp = qfCourseDao.findCourseDetailById(id);

        return new BaseResult(1,"查询成功！",courseTeacherResp,null);
    }
}
